package com.example.mardan_demo1.config;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 打印请求方法和参数
 */
@Component
public class RequestLoggingInterceptor implements HandlerInterceptor {

    // ANSI 转义码
    private static final String RED_COLOR = "\\u001B[31m";
    private static final String RESET_COLOR = "\\u001B[0m";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 打印请求方法和参数
        System.out.println("请求方法：" + request.getMethod());
        // 打印请求url
        System.out.println("请求路径：" + request.getRequestURI());
        // 打印请求头中的Authorization
        String authorization = request.getHeader("Authorization");
        if (authorization != null) {
            System.out.println("Authorization: " + authorization);
        } else {
            System.out.println("Authorization header is not present.");
        }
        // 打印请求参数
        // 获取并打印请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            String[] values = entry.getValue();
            System.out.println("全局参数打印机: " + key + " = " + String.join(", ", values));
        }
        return true;
    }
}
